from flask import request, Blueprint

from api.decorators import cache
from api.slider import get_json_response, get_book_source, get_chapter_by_source_id, get_book_chapter_content, \
    get_book_info, get_search_content, encode_chapter_link

book = Blueprint('book', __name__)


# 获取书籍信息
@book.route('/bookInfo/<_id>')
@cache
def book_info_response(_id):
    content = get_book_info(_id)
    return get_json_response(content, request)


# 获取书籍正版源于盗版源(混合)
@book.route('/book/source/bookId/<book_id>')
@cache
def book_source_response(book_id):
    content = get_book_source(book_id)
    return get_json_response(content, request)


def get_chapter_by_the_one_source(book_id):
    source_list = get_book_source(book_id)
    content = get_chapter_by_source_id(source_list[0]['_id'])
    return content


# 获取书籍章节(根据书籍id)
@book.route('/book/chapter/bookId/<book_id>')
@cache
def book_chapter_by_book_id_response(book_id):
    content = get_chapter_by_the_one_source(book_id)
    return get_json_response(content, request)


# 获取书籍章节(根据书籍源id)
@book.route('/book/chapter/sourceId/<source_id>')
@cache
def book_chapter_by_source_id_response(source_id):
    content = get_chapter_by_source_id(source_id)
    return get_json_response(content, request)


@book.route('/book/chapter')
@cache
def book_chapter_response():
    book_id = request.args.get('bookId', '')
    source_id = request.args.get('sourceId', '')
    if source_id:
        return book_chapter_by_source_id_response(source_id)
    else:
        return book_chapter_by_book_id_response(book_id)


# 获取书籍章节内容
@book.route('/book/content')
@cache
def book_chapter_content():
    chapter_link = request.args.get('link', '')
    chapter_link = encode_chapter_link(chapter_link)
    content = get_book_chapter_content(chapter_link)
    return get_json_response(content, request)


# 书籍搜索
@book.route('/search')
@cache
def search_response():
    query = request.args.get('query', '231')
    start = request.args.get('start', 1, int) - 1
    limit = request.args.get('limit', 100, int)
    content = get_search_content(query, start * limit, limit)
    return get_json_response(content, request)
